import {IncomingMessage} from "http"
import {formatRequestPathWithQueryString} from "../../support/util/path"



export type HttpRequestFacade = IncomingMessage & {
  params: any
  setParam: (key: string, value: any) => void
  query: Record<string, string>
  isJson: boolean
}

export function createRequestFacade(request: any): HttpRequestFacade {
  request.params = {}

  // 注入query,标准化url
  const [path, query] = formatRequestPathWithQueryString(request.url)
  request.url = path
  request.query = query


  // 注入setParam方法
  request.setParam = (key, val) => request.params[key] = val

  // 注入isJson
  const headers = request.headers
  const contentType = headers["content-type"] || headers["Content-Type"]
  request.isJson = contentType && contentType.startsWith("application/json")

  return request
}

